/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo;

import clases.Cliente;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author togapaulo
 */
public class MdlCliente implements Modelo<Cliente>{

    /**
     * 
     * @param cliente
     * @param cnx
     * @throws SQLException 
     */
    @Override
    public void insert(Cliente cliente, Conexion cnx) throws SQLException {
        String sql = "INSERT INTO Cliente(nombre, dni)"
                + "VALUES ('" + cliente.getNombre() + "','" + cliente.getDni() + "');";
        cnx.ejecutar(sql);
    }

    /**
     * 
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public int getLastId(Conexion cnx) throws SQLException {
        String sql = "SELECT idCliente FROM Cliente ORDER BY idCliente DESC LIMIT 1";
        ResultSet rs = cnx.consultar(sql);
        if (rs.next()) {
            return rs.getInt(1);
        }
        return -1;
    }

    /**
     * 
     * @param cliente
     * @param cnx
     * @throws SQLException 
     */
    @Override
    public void update(Cliente cliente, Conexion cnx) throws SQLException {
        String sql = "UPDATE Cliente SET"
                + "nombre = '" + cliente.getNombre() + "' "
                + "dni = '" + cliente.getDni() + "' "
                + "WHERE idCliente = " + cliente.getIdCliente();
        cnx.ejecutar(sql);
    }

    /**
     * 
     * @param query
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public ArrayList<Cliente> get(String query, Conexion cnx) throws SQLException {
        String sql = "SELECT * FROM Cliente WHERE nombre LIKE '%" + query + "%';";
        ResultSet rs = cnx.consultar(sql);
        ArrayList<Cliente> clientes = new ArrayList<>();
        
        while(rs.next()){
            Cliente cliente;
            cliente = new Cliente(rs.getInt("idCliente"),
                    rs.getString("nombre"),
                    rs.getString("dni"));
            clientes.add(cliente);
        }
        return clientes;
    }

    /**
     * 
     * @param idCliente
     * @param cnx
     * @return
     * @throws SQLException 
     */
    @Override
    public Cliente get(int idCliente, Conexion cnx) throws SQLException {
        String sql = "SELECT * FROM Cliente WHERE idCliente LIKE " + idCliente;
        ResultSet rs = cnx.consultar(sql);
        Cliente cliente = null;
        
        if (rs.next()) {
            cliente = new Cliente(rs.getInt(1),rs.getString(2),rs.getString(3));
        }
        return cliente;
    }
    
}
